package com.lry.netty01.server.queue;

import com.lry.netty01.server.entity.FixedFrame;
import com.lry.netty01.server.entity.Packet;
import com.lry.netty01.server.utils.ChannelUtil;
import com.lry.netty01.server.utils.CommandUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Task implements Runnable{

        private Packet packet;


        public Task(Packet packet){
            this.packet = packet;
        }

        @Override
        public void run() {
            boolean isUp = packet.isUp;
            FixedFrame fixedFrame = packet.request;
            //客户端发给服务端的报文, 注册（第一次发送），报警（定时发送）
            if(isUp){
                packet.channel.writeAndFlush(fixedFrame);
                //如果是客户端发给服务器的注册包，则加入到半完成队列
                if(fixedFrame.getCmd()==CommandUtil.REGISTER_CMD){
                    ChannelUtil.pendingQueue.add(packet);
                }

            }
            //服务器下发给客户端的报文，操作,心跳,注册响应
            else{
                byte cmd = fixedFrame.getCmd();

                if(cmd==CommandUtil.HEART_BEAT_CMD){
                    log.info("收到心跳包");
                    //回发心跳包
                    packet.channel.writeAndFlush(fixedFrame);
                }else if(cmd==CommandUtil.OPERATE_CMD){
                    log.info("收到温度设置包");
                    //收到服务端的温度设置指令，调用硬件去设置温度，设置成功回发指令
                    //回发温度报警包
                    fixedFrame.setCmd(CommandUtil.WARNING_CMD);
                    packet.channel.writeAndFlush(fixedFrame);

                }else if(cmd==CommandUtil.REGISTER_CMD){
                    log.info("收到注册成功包");
                    //如果收到了服务端回应的注册包，则从半完成队列拿出packet，notifyAll
                    Packet packet = ChannelUtil.pendingQueue.remove();
                    if(null==packet)
                        return;
                    synchronized (packet){
                        packet.response = fixedFrame;
                        packet.finished = true;
                        packet.notifyAll();
                    }
                }

            }


        }

    }